
from pydub import AudioSegment
import wave
import io

'''
https://zhuanlan.zhihu.com/p/91257681



'''

def mp3_to_wav(mp3_path, wav_path):
    """
    mp3 转 wav
    :param mp3_path: 输入的 mp3 路径
    :param wav_path: 输出的 wav 路径
    :return: 
    """
    # 读取 mp3
    fp = open(mp3_path, 'rb')
    data = fp.read()
    fp.close()
    # 读取
    aud = io.BytesIO(data)
    song = AudioSegment.from_file(aud, format='mp3')

    start_seconds = 30 * 1000
    seconds = 60 * 1000
    t_seconds = song[start_seconds:(start_seconds+seconds)]
    last_5_seconds = song[-5000:]

    sound = t_seconds
    #sound = song

    raw_data = sound._data

    # 写入 wav
    nframes = len(raw_data)
    print("nframes=", nframes)

    f = wave.open(wav_path, 'wb')
    f.setnchannels(2)
    f.setsampwidth(2)
    f.setframerate(41400)
    f.setnframes(nframes)
    f.writeframes(raw_data)
    f.close()


def test(source_file_path, destin_path):
    sound = AudioSegment.from_mp3(source_file_path)
    sound.export(destin_path, format='wav')

if __name__ == '__main__':
    #mp3_to_wav('01chunzhen.mp3', '3_s10.wav')
    mp3_to_wav('../audio/angel.mp3', 'angel.wav')
    #mp3_to_wav('happy.mp3', 'happy_20.wav')



